package com.mall507.fivepeaks.widget.xdialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hzh.frame.util.AndroidUtil;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.activity.community.CommunityBusinessStoreInfoRUI;

import java.util.List;

/**
 * 跳转地图选择
 * */
public class XAddressDialog {

	private Dialog alertDialog;
	
	/**
	 * @param context
	 * @param callback 选择结果回调
	 * */
	public void show(final Context context, final String address, final String lat, final String lng, final XUserMainSignRewardDialogCallBack callback) {
		//防止网络延迟情况下多次点击弹出多个窗口
		dismiss();
		alertDialog = new Dialog(context, R.style.chooseDialog);
		LayoutInflater in = LayoutInflater.from(context);
		View viewDialog = in.inflate(R.layout.view_xdialog_address, null);
		
		TextView cancel= viewDialog.findViewById(R.id.cancel);
		TextView close = viewDialog.findViewById(R.id.close);
		LinearLayout baidu = viewDialog.findViewById(R.id.baidu);
        LinearLayout gaode = viewDialog.findViewById(R.id.gaode);
        LinearLayout tencent = viewDialog.findViewById(R.id.tencent);
        Double latitude = 0.0;
        Double lngitude = 0.0;
        if (lat != null && lat.length()>0 && lng != null && lng.length()>0){
            latitude = Double.parseDouble(lat);
            lngitude = Double.parseDouble(lng);
        }
		close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                callback.cancel();
            }
        });
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				dismiss();
				callback.cancel();
			}
		});
        final Double finalLatitude = latitude;
        final Double finalLngitude = lngitude;
        baidu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                goToBaiduMap(context,address);
                toBaiduMap(context,address, finalLatitude, finalLngitude);
                dismiss();
            }
        });
		gaode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                goToGaodeMap(context,address);
                dismiss();
            }
        });
		tencent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                goToTencentMap(context,address);
                dismiss();
            }
        });
        int width = AndroidUtil.getWindowWith();
        int height = AndroidUtil.getWindowHeight();
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width, height);
		alertDialog.setContentView(viewDialog,layoutParams);
		// 点击对话框外部取消对话框显示
		alertDialog.setCanceledOnTouchOutside(true);
		alertDialog.show();
	}
	
	/**
	 * 关闭当前Dialog
	 * */
	public void dismiss(){
		if(alertDialog!=null && alertDialog.isShowing()){
			alertDialog.dismiss();
		}
	}

	
    /**
	 * 选择结果回调
	 * */
	public interface XUserMainSignRewardDialogCallBack{
		  /**
		   * 确定
		   */
		  void confirm();
		  
		  /**
		   * 取消
		   */
		  void cancel();
	}

    /**
     * 检测程序是否安装
     *
     * @param packageName
     * @return
     */
    private boolean isInstalled(String packageName,Context context) {
        PackageManager manager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

    /**
     * 跳转百度地图
     */
    private void goToBaiduMap(Context context,String address) {
        if (!isInstalled("com.baidu.BaiduMap",context)) {
//            alert("请先安装百度地图客户端");
            Toast.makeText(context,"请先安装百度地图客户端",Toast.LENGTH_LONG).show();
            return;
        }
        try {
            Intent i1 = new Intent();
            i1.setData(Uri.parse("baidumap://map/geocoder?src=openApiDemo&address=" + address));
            context.startActivity(i1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
//    * 打开百度地图（公交出行，起点位置使用地图当前位置）
//            *
//            * mode = transit（公交）、driving（驾车）、walking（步行）和riding（骑行）. 默认:driving
// * 当 mode=transit 时 ： sy = 0：推荐路线 、 2：少换乘 、 3：少步行 、 4：不坐地铁 、 5：时间短 、 6：地铁优先
// *
//         * @param dlat  终点纬度
// * @param dlon  终点经度
// * @param dname 终点名称
// */
    private void toBaiduMap(Context context,String address,Double dlat,Double dlon) {
        if (!isInstalled("com.baidu.BaiduMap",context)) {
            //            alert("请先安装百度地图客户端");
            Toast.makeText(context,"请先安装百度地图客户端",Toast.LENGTH_LONG).show();
            return;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("baidumap://map/direction?origin=我的位置&destination=name:"
                    + address
                    + "|latlng:" + dlat + "," + dlon
                    + "&mode=driving&sy=0&&target=1"));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转高德地图
     */
    private void goToGaodeMap(Context context,String address) {
        if (!isInstalled("com.autonavi.minimap",context)) {
//            alert("请先安装高德地图客户端");
            Toast.makeText(context,"请先安装高德地图客户端",Toast.LENGTH_LONG).show();
            return;
        }
        try {
            String act = "android.intent.action.VIEW";
            String dat = "androidamap://keywordNavi?sourceApplication=softname&keyword=" + address + " &style=2";
            String pkg = "com.autonavi.minimap";
            Intent intent = new Intent(act, Uri.parse(dat));
            intent.setPackage(pkg);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转腾讯地图
     */
    private void goToTencentMap(Context context,String address) {
        if (!isInstalled("com.tencent.map",context)) {
//            alert("请先安装腾讯地图客户端");
            Toast.makeText(context,"请先安装腾讯地图客户端",Toast.LENGTH_LONG).show();
            return;
        }
        try {
            String pathUrl = "qqmap://map/routeplan?type=drive&to=" + address + "&tocoord=" + "" + "," + "" + "&policy=2&referer=myapp";
            Intent intent = new Intent();
            intent.setData(Uri.parse(pathUrl));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
